
local cc_shared_dict = {}

local cc_dict = ngx.shared.cls_waf_cc_dict

cc_shared_dict.init = function()
    -- 在此处理一些初始化业务
end

cc_shared_dict.set = function(key, value, timeout)
    local ok, _ = nil, nil
    if timeout > 0 then
        ok, _ = cc_dict:set(key, value, timeout)
        if not ok then
            ngx.log( ngx.ERR, "shared_dict SET failed ")
            return
        end
    else
        ok, _ = cc_dict:set(key, value)
        if not ok then
            ngx.log( ngx.ERR, "shared_dict SET failed ")
            return
        end
    end
    return ok
end

cc_shared_dict.incr = function(key)
    local newval, _ = cc_dict:incr(key, 1)
    if not newval then
        ngx.log( ngx.ERR, "shared_dict INCR failed ")
        return
    end
    return newval
end

cc_shared_dict.get = function(key)
    local res, flag = cc_dict:get(key)
    if not res then
        -- ngx.log( ngx.ERR, "shared_dict GET failed : "..key)
        return
    end
    return res
end

cc_shared_dict.set_ip = function(ip, timeout)
    local ipkey = g_ccip_prefix..ip
    local ok, _ = nil, nil
    if timeout > 0 then
        ok, _ = cc_dict:set(ipkey, 1, timeout)
        if not ok then
            ngx.log( ngx.ERR, "shared_dict SET failed ")
            return
        end
    else
        ok, _ = cc_dict:set(ipkey, 1)
        if not ok then
            ngx.log( ngx.ERR, "shared_dict SET failed ")
            return
        end
    end
    return ok
end

cc_shared_dict.ip_exist = function(ip)
    local ipkey = g_ccip_prefix..ip
    local res, flag = cc_dict:get(ipkey)
    if not res then
        return false
    end

    return true
end

cc_shared_dict.clean_all_ccip = function()
    local all_keys = cc_dict:get_keys(0)
    for _, key in pairs(all_keys) do
        local from, to, err = ngx.re.find(key, g_ccip_prefix, 'ijo')
        if from then
            cc_dict:delete(key)
        end
    end
end

return cc_shared_dict
